/*
 * Copyright 2024 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.pajamas.daydream.serializer.json;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.pajamas.protocol.Serializer;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Map;

import lombok.extern.slf4j.Slf4j;

/**
 * @author william
 * @since 2024/1/1
 */
@Slf4j
public abstract class AbstractJsonSerializer implements Serializer {

    /**
     * {@code T} not supported to define abstract-type (test with jackson and gson)
     */
    public abstract <T> List<T> objectifyList(String text, Class<T> clz);

    public abstract <K, V> Map<K, V> objectifyMap(String text, Class<K> keyClz, Class<V> valClz);

    @Override
    public <T> T objectify(File file, Class<T> clz) throws IOException {
        String text = this.stringify(file);
        return this.objectify(text, clz);
    }

    public <T> List<T> objectifyList(File file, Class<T> clz) throws IOException {
        String text = this.stringify(file);
        return this.objectifyList(text, clz);
    }

    public <K, V> Map<K, V> objectifyMap(File file, Class<K> keyClz, Class<V> valClz) throws IOException {
        String text = this.stringify(file);
        return this.objectifyMap(text, keyClz, valClz);
    }

    @Override
    public String stringify(File file) throws IOException {
        return FileUtils.readFileToString(file, Charset.defaultCharset());
    }

    @Override
    public <T> void placeToFile(T object, File file) throws IOException {
        if (object == null) {
            log.warn("placeToFile skip ... object is null");
            return;
        }
        String text = this.stringify(object);
        this.placeToFile(text, file);
    }

    @Override
    public void placeToFile(String text, File file) throws IOException {
        if (StringUtils.isBlank(text)) {
            log.warn("placeToFile skip ... text is blank");
            return;
        }
        FileUtils.writeStringToFile(file, text, Charset.defaultCharset());
    }
}
